//
//  NetworkHandler.m
//  解析电影信息
//
//  Created by chenTengfei on 14-9-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NetworkHandler.h"

@implementation NetworkHandler

+ (NSData *)getConnectionWithURL:(NSString *)address
{
    // 将地址转换为URL格式
    NSString *newAdd = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *urlAdd = [NSURL URLWithString:newAdd];
    
    // 创建一个请求,不带本地缓存
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlAdd cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"get";
    
    __block NSData *result;
    
    // 连接服务器(异步)
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSLog(@"---response---: %@", response);
        NSLog(@"---error---: %@", connectionError);
        
        result = data;
    }];
    return result;
}

+ (void)getConnectionWithURL:(NSString *)address completion:(void(^)(id result))block
{
    // 将地址转换为URL格式
    NSString *newAdd = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *urlAdd = [NSURL URLWithString:newAdd];
    
    // 创建一个请求,不带本地缓存
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlAdd cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    request.HTTPMethod = @"get";
    
    
    // 连接服务器(异步)
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSLog(@"---response---: %@", response);
        NSLog(@"---error---: %@", connectionError);
        
        NSInteger number = [address hash];
        NSString *LibraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSString *docPath = [NSString stringWithFormat:@"Caches/%d.txt",number];
        
        if (data != nil) {
            //数据保存到本地
            [data writeToFile:[LibraryPath stringByAppendingPathComponent:docPath]  atomically:YES];
        } else {
            // 读取本地数据
            data = [NSData dataWithContentsOfFile:[LibraryPath stringByAppendingPathComponent:docPath]];
        }
        
        // JSON 解析
        if (data != nil) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            // 解析后的结果,通过block参数使用
            block(result);
        }
        
    }];
}

@end
